package com.example.openai.filter;

import com.example.openai.model.LoginUser;
import com.example.openai.util.JwtUtil;
import com.example.openai.util.RedisCache;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader("token");
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        String userId="";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        LoginUser cacheObject = redisCache.getCacheObject("login:" + userId);

//        System.out.println(cacheObject.getAuthorities());
        if(Objects.nonNull(cacheObject)){
            UsernamePasswordAuthenticationToken token1=new UsernamePasswordAuthenticationToken(cacheObject,null,cacheObject.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(token1);
        }

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
